// pages/editor/editor.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    longname:"",
    name:"",
    address:"",
    imgList: [],
    content:'',

    values: "",
    texts: "",
    min: 10,//最少字数
    max: 100, //最多字数 
  },

  //字数限制
  inputs: function (e) {
    // 获取输入框的内容
    var value = e.detail.value;
    // 获取输入框内容的长度
    var len = parseInt(value.length);
    //最少字数限制
    if (len <this.data.min){
      this.setData({
        texts: "至少要输入10个字哦"
      })
    }else if (len >= this.data.min){
      this.setData({
        values: value,
        texts: " "
      })
    }
    //最多字数限制
    if (len > this.data.max) return;
    // 当输入框内容的长度大于最大长度限制（max)时，终止setData()的执行
    this.setData({
      currentWordNumber: len //当前字数  
    });
  },

  //选择地理位置
  chooseLocation:function(){
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        //完整的名字存入longname
        that.setData({
          longname: res.name,
        })
        //长度大于15截取
        if(res.name.length > 15){
          var shortname = res.name.slice(0,15)
          that.setData({
            name: shortname + '...',
            address: res.address,
          }) 
        }else{
          that.setData({
            name: res.name,
            address: res.address,
          }) 
        }
      },
    })
  },

  chooseSource: function() {
    var _this = this;
    wx.showActionSheet({
      itemList: ["拍照", "从相册中选择"],
      itemColor: "#CED63A",
      success: function(res) {
        if(!res.cancel) {
          if(res.tapIndex == 0) {
            _this.imgWShow("camera")        //拍照
          } else if (res.tapIndex == 1) {
            _this.imgWShow("album")      //相册
          }
        }
      }
    })
  },
  // 点击调用手机相册/拍照
  imgWShow: function(type) {
    var _this = this;
    let len = 0;
    if(_this.data.imgList != null) {
      len = _this.data.imgList.length
    }   
    //获取当前已有的图片
    wx.chooseImage({
      count: 6-len,     //最多还能上传的图片数,这里最多可以上传5张
      sizeType: ['original', 'compressed'],        //可以指定是原图还是压缩图,默认二者都有
      sourceType: [type],             //可以指定来源是相册还是相机, 默认二者都有
      success: (res) => {
        wx.showToast({
          title: '正在上传...',
          icon: "loading",
          mask: true,
          duration: 1000
        })
        // 返回选定照片的本地文件路径列表,tempFilePaths可以作为img标签的scr属性显示图片
        var imgList = res.tempFilePaths
        let tempFilePathsImg = _this.data.imgList
        // 获取当前已上传的图片的数组
        var tempFilePathsImgs = tempFilePathsImg.concat(imgList)
        this.setData({
          imgList: tempFilePathsImgs
        })
      },
      fail: function () {
        wx.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
        return;
      }
    })
  },
  // 预览图片
  previewImg: function(e) {
    let index = e.target.dataset.index;
    let _this = this;
    wx.previewImage({
      current: _this.data.imgList[index],
      urls: _this.data.imgList
    })
  },
  // 点击删除
  deleteImg: function(e) {
    var _this = this;
    var imgList = _this.data.imgList;
    var index = e.currentTarget.dataset.index;   //获取当前点击图片下标
    wx.showModal({
      title: '提示',
      content: '确认要删除该图片吗?',
      success: (res) => {
        if(res.confirm) {
          console.log("点击确定了")
          imgList.splice(index, 1);
        } else if (res.cancel) {
          console.log("点击取消了");
          return false
        }
        _this.setData({
          imgList
        })
      }
    })
  },

//点击按钮后提交数据
submit:function(){
  //如果定位为空，则传“未进行定位”
  if(!this.data.longname)
    this.data.longname = "未进行定位"
  //获得时间
  var util = require('../utils/util.js');
  var time = util.formatTime(new Date())
  this.setData({//为页面中time赋值
    time:time
  })
  //获得内容
  const dataValue = this.data.values
  //获得地点
  const localName = this.data.longname
  //获得用户id
  var userid = wx.getStorageSync('userid');
  //获取用户组
  let groupid=wx.getStorageSync('groupid')
  //获得图片数组
  let img_url = this.data.imgList;

  //如果图片数组为空
  if(img_url.length==0){
    wx.request({
      url : "https://www.prebeauty.work:3001/api/says",
      data: {
        userid: userid,
        saycontent :dataValue,
        saytime: time,
        sayimg : JSON.stringify(img_url),
        saylocal : localName,
        groupid: groupid,
      },
      method: "POST",
      header: {
        "content-type": "application/json"
      },
      success:(res)=>{
        console.log(res.data)
        this.setData({
          sayid:res.data
        })
        this.postlike()
        wx.showToast({
          title: '发布成功！',
          icon: 'success',
          duration: 2000
        })
        wx.redirectTo({
          url: `/detail/userpage/userpage?userid=${userid}`, //跳转到userpage页面
        })
      }
    })
  }else{
    //如果数组不为空，就一张张上传图片
    console.log(1)
    let img_url_ok = [];
    for (let i = 0; i < img_url.length; i++) {
      wx.uploadFile({
        //路径填上传图片方法的地址
        filePath: img_url[i],
        name: 'image',
        header: {
          'content-type': 'multipart/form-data'
        },
        url: 'https://www.prebeauty.work:3001/api/upload',
        success: (res) => {
          console.log('上传成功');
          //把上传成功的图片的地址放入数组中
          img_url_ok.push(res.data)  
          console.log(img_url_ok)
          //全部图片上传成功后发送post请求
          if (img_url_ok.length == img_url.length) {
              wx.request({
                url : "https://www.prebeauty.work:3001/api/says",
                method: "POST",
                data: {
                  userid: userid,
                  saycontent :dataValue,
                  saytime: time,
                  sayimg : JSON.stringify(img_url_ok),
                  saylocal : localName,
                  groupid: groupid,
                },
                header: {
                  "content-type": "application/json"
                },
                success: (res) => {
                  console.log(res.data)
                  this.setData({
                    sayid:res.data
                  })
                  this.postlike()
                  wx.showToast({
                    title: '发布成功！',
                    icon: 'success',
                    duration: 2000
                  })
                  wx.redirectTo({
                    url: `/detail/userpage/userpage?userid=${userid}`, //跳转到userpage页面
                  })
              },
            })
          }
        } 
      })
    }
  }
},

  postlike:function(){
     //获取所有用户id
    wx.request({
      url: 'https://www.prebeauty.work:3001/api/userpage',
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      success:async (res)=>{
        console.log(res.data)
        console.log(this)
        this.setData({
          userlist:res.data
        })
        
        await new Promise((rv,rj)=>{
          let users=this.data.userlist
          for(let i=0;i<users.length;i++){
            //向like表中添加信息
            wx.request({
              url: 'https://www.prebeauty.work:3001/api/like',
              data:{
                sayid:this.data.sayid,
                userid:users[i].userid,
                islike:'false',
                likeimg:'/icon/like.png'
              },
              header: {
                'content-type': 'application/json'
              },
              method: 'POST',
              success: (res)=>{
                console.log('post like success!')
                rv()
              }, 
              fail:err=>{
                rv()
              }
            })
          }
        })  
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(wx.getStorageSync('userid'))
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(!wx.getStorageSync('token')){
      wx.showModal({
        title: '用户未登录',
        content: '请先进行授权登录',
        success(res) {
          if (res.confirm) {
            console.log('确定')
            wx.switchTab({
              url: '/pages/home/home'
           })
          } else if (res.cancel) {
            console.log('取消')
            wx.switchTab({
              url: '/pages/index/index'
           })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})